package com.xjscrm.server.service.tasktagkeyword.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.google.common.collect.Lists;
import com.uzai.mobile.collect.api.MicaTopics;
import com.uzai.mobile.collect.api.dto.MicaTransDto;
import com.uzai.mobile.collect.api.dto.MicaTriggerDto;
import com.uzai.mobile.collect.api.dto.msg.MicaFriendTalkMsg;
import com.uzai.mobile.collect.api.dto.msg.consertoserver.MicaCustomerAddTagMsg;
import com.uzai.mobile.collect.api.dto.trigger.MicaTriggerBatchMarkLabelMsg;
import com.uzai.mobile.collect.api.dto.trigger.talk.MicaTalkContentTextMsg;
import com.uzai.mobile.collect.api.enums.MicaTalkMsgType;
import com.uzai.mobile.collect.api.enums.MicaTriggerType;
import com.uzai.trace.TraceGenerate;
import com.xjscrm.common.entity.*;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.Tools;
import com.xjscrm.server.biz.mq.producer.SendMsgProducer;
import com.xjscrm.server.common.util.DeviceTools;
import com.xjscrm.server.common.util.Functions;
import com.xjscrm.server.mapper.*;
import com.xjscrm.server.service.grouppull.GroupPullConfigService;
import com.xjscrm.server.service.soptask.SopJobTagService;
import com.xjscrm.server.service.tasktagkeyword.TaskTagKeywordService;
import com.xjscrm.server.vo.device.Device;
import com.xjscrm.server.vo.tasktagkeyword.TaskTagKeywordVerifyResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 客户聊天好友申请实现类
 *
 * @author makejava
 * @since 2024-03-01 17:01:12
 */
@Slf4j
@Service
public class TaskTagKeywordServiceImpl implements TaskTagKeywordService {

    @Autowired
    private WwDeviceMapper wwDeviceMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TaskTagKeywordDeviceMapper taskTagKeywordDeviceMapper;
    @Autowired
    private WwTagsMapper wwTagsMapper;
    @Autowired
    private WwCustomerMapper wwCustomerMapper;
    @Autowired
    private WwCustomerTagsMapper wwCustomerTagsMapper;
    @Autowired
    private SendMsgProducer sendMsgProducer;
    @Autowired
    private WwCustomerBlacklistMapper wwCustomerBlacklistMapper;
    @Autowired
    private SopJobTagService sopJobTagService;
    @Autowired
    private GroupPullConfigService groupPullConfigService;

    /**
     * 客户往机器人发送聊天消息
     *
     * @param micaTransDto 客户往机器人发送聊天消息
     * @return 实例对象
     */
    @Async("taskExecutorForEvent")
    @TraceGenerate //注入消息id标签
    public void friendTalkToDevice(MicaTransDto micaTransDto) {

        try {
            log.info("--监控系统日志--开始--");
            MicaFriendTalkMsg micaFriendTalkMsg = JSONObject.parseObject(micaTransDto.getData().toString(), MicaFriendTalkMsg.class);

            if (StringUtils.isBlank(micaTransDto.getDeviceId())) {
                log.info("机器人wxid is null, merId={}", micaTransDto.getMerId());
                return;
            }

            //查询该机器人的配置方案
            log.info("--监控系统日志--查询机器人--");
            WwDevice wwDevice = wwDeviceMapper.queryByDeviceId(micaTransDto.getDeviceId(), micaTransDto.getMerId());
            if (wwDevice == null) {
                return;
            }
            Device device = DeviceTools.transDevice(wwDevice);
            if (device == null) {
                return;
            }

            //默认黑名单不通过、
            log.info("--监控系统日志--查询黑名单--");
            WwCustomerBlacklist wwCustomerBlacklist = wwCustomerBlacklistMapper.selectByWxid(micaTransDto.getMerId(), micaFriendTalkMsg.getSendWxId());
            if(wwCustomerBlacklist != null){ //在黑名单中
                log.info("黑名单会员，wxid={}", micaFriendTalkMsg.getSendWxId());
                return ;
            }


            //只支持文本消息
            if (micaFriendTalkMsg.getMsgType().intValue() != MicaTalkMsgType.TEXT.getCode().intValue()) {
                return;
            }

            //聊天消息
            MicaTalkContentTextMsg textContent = micaFriendTalkMsg.getTextContent();
            if (textContent == null) {
                return;
            }
            String msg = textContent.getText(); //聊天信息

            if (StringUtils.isBlank(msg)) {
                return;
            }

            //增加会员标签
            WwCustomer wwCustomer = wwCustomerMapper.queryByDeviceUniqueIdAndWxid(device.getDeviceUniqueId(), micaFriendTalkMsg.getSendWxId());
            if (wwCustomer == null) {
                return;
            }

            //当前时间
            int now = DateUtil.getTime();

            //是否成功打标签判断
            boolean addTagFlag = false;

            //查询该机器人配置的客户私聊关键词打标签
            List<TaskTagKeywordDevice> taskTagKeywordDevices = taskTagKeywordDeviceMapper.selectByDeviceUniquIdAndTriggerType(device.getDeviceUniqueId(), "0");
            if (taskTagKeywordDevices != null) {
                for (TaskTagKeywordDevice taskTagKeywordDevice : taskTagKeywordDevices) {
                    List<Long> tagIdList = JSONObject.parseArray(taskTagKeywordDevice.getEnterpriseTags(), Long.class);
                    if (tagIdList != null && tagIdList.size() >= 0) {
                        TaskTagKeywordVerifyResult taskTagKeywordVerifyResult = verifyPara(taskTagKeywordDevice, msg, device);
                        //通过，则修改标签，并发送指令
                        if (taskTagKeywordVerifyResult != null && taskTagKeywordVerifyResult.isPass()) {
                            for (Long tagId : tagIdList) {
                                //判断该会员是否已经打了此标签
                                WwTags wwTags = wwTagsMapper.queryById(tagId);
                                if (wwTags != null) {
                                    WwCustomerTags wwCustomerTags = wwCustomerTagsMapper.queryByCustomerIdAndTagId(wwCustomer.getId(), tagId);
                                    if (wwCustomerTags == null) {//没有打此标签，则需要打标签
                                        wwCustomerTags = new WwCustomerTags();
                                        wwCustomerTags.setId(IdWorker.getId());
                                        wwCustomerTags.setTagId(tagId);
                                        wwCustomerTags.setTagIdStr(wwTags.getTagId());
                                        wwCustomerTags.setCustomerId(wwCustomer.getId());
                                        wwCustomerTags.setMerId(device.getMerId());
                                        wwCustomerTags.setCreateTime(now);
                                        wwCustomerTags.setUpdateTime(now);
                                        wwCustomerTagsMapper.insert(wwCustomerTags);
                                        groupPullConfigService.groupPushByEnterpriseTag(device, wwCustomer, wwCustomerTags.getTagId());

                                        addTagFlag = true;

                                        log.info("--监控系统日志--输入会员标签数据--");

                                        //发送打标签指令
                                        try {
                                            MicaTriggerBatchMarkLabelMsg micaTriggerBatchMarkLabelMsg = new MicaTriggerBatchMarkLabelMsg();
                                            micaTriggerBatchMarkLabelMsg.setLabelId(wwTags.getTagId());
                                            micaTriggerBatchMarkLabelMsg.setIsCorp(Tools.getInteger(wwTags.getType()).intValue() == 1 ? true : false); //是否是企业标签
                                            micaTriggerBatchMarkLabelMsg.setAddWxIds(Lists.newArrayList(wwCustomer.getWxid()));
                                            MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerBatchMarkLabelMsg, MicaTriggerType.TRIGGER_BATCH_MARK_LABEL, Functions.fillTriggerMsg(device));
                                            sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC); //存放瞬时消息
                                        } catch (Exception e) {
                                            log.error("{}", e);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            if(addTagFlag){
                //触发SOP任务-自动打标签
                sopJobTagService.addSopJobByPushCustomerTag(micaTransDto.getMerId(), wwDevice, wwCustomer);
            }

        }catch (Exception e){
            log.error(e.getMessage() , e);
        }finally {
            log.info("--监控系统日志--结束--");
        }

    }

    /**
     * 机器人往客户发送聊天消息
     *
     * @param micaTransDto 机器人往客户发送聊天消息
     * @return 实例对象
     */
    @Async("taskExecutorForEvent")
    @TraceGenerate //注入消息id标签
    public void deviceTalkToFriend(MicaTransDto micaTransDto) {

        try {
            log.info("--监控系统日志--开始--");

            MicaFriendTalkMsg micaFriendTalkMsg = JSONObject.parseObject(micaTransDto.getData().toString(), MicaFriendTalkMsg.class);
            if(micaFriendTalkMsg == null){
                return;
            }

            //默认黑名单不通过
            WwCustomerBlacklist wwCustomerBlacklist = wwCustomerBlacklistMapper.selectByWxid(micaTransDto.getMerId(), micaFriendTalkMsg.getSendWxId());
            if(wwCustomerBlacklist != null){ //在黑名单中
                log.info("黑名单会员wxid={}, merId={}", micaFriendTalkMsg.getSendWxId(),micaTransDto.getMerId());
                return;
            }

            if (StringUtils.isBlank(micaTransDto.getDeviceId())) {
                log.info("机器人wxid is null, merId={}", micaTransDto.getMerId());
                return;
            }

            //查询该机器人的配置方案
            WwDevice wwDevice = wwDeviceMapper.queryByDeviceId(micaTransDto.getDeviceId(), micaTransDto.getMerId());
            if (wwDevice == null) {
                return;
            }
            Device device = DeviceTools.transDevice(wwDevice);
            if (device == null) {
                return;
            }

            //只支持文本消息
            if (micaFriendTalkMsg.getMsgType().intValue() != MicaTalkMsgType.TEXT.getCode().intValue()) {
                return;
            }

            //聊天消息
            MicaTalkContentTextMsg textContent = micaFriendTalkMsg.getTextContent();
            if (textContent == null) {
                return;
            }
            String msg = textContent.getText(); //聊天信息

            if (StringUtils.isBlank(msg)) {
                return;
            }

            //增加会员标签
            WwCustomer wwCustomer = wwCustomerMapper.queryByDeviceUniqueIdAndWxid(device.getDeviceUniqueId(), micaFriendTalkMsg.getSendWxId());
            if (wwCustomer == null) {
                return;
            }

            //当前时间
            int now = DateUtil.getTime();

            //查询该机器人配置的客户私聊关键词打标签
            List<TaskTagKeywordDevice> taskTagKeywordDevices = taskTagKeywordDeviceMapper.selectByDeviceUniquIdAndTriggerType(device.getDeviceUniqueId(), "1");
            if (taskTagKeywordDevices != null) {
                for (TaskTagKeywordDevice taskTagKeywordDevice : taskTagKeywordDevices) {
                    List<Long> tagIdList = JSONObject.parseArray(taskTagKeywordDevice.getEnterpriseTags(), Long.class);
                    if (tagIdList != null && tagIdList.size() >= 0) {
                        TaskTagKeywordVerifyResult taskTagKeywordVerifyResult = verifyPara(taskTagKeywordDevice, msg, device);
                        //通过，则修改标签，并发送指令
                        if (taskTagKeywordVerifyResult != null && taskTagKeywordVerifyResult.isPass()) {
                            for (Long tagId : tagIdList) {
                                //判断该会员是否已经打了此标签
                                WwTags wwTags = wwTagsMapper.queryById(tagId);
                                if (wwTags != null) {
                                    WwCustomerTags wwCustomerTags = wwCustomerTagsMapper.queryByCustomerIdAndTagId(wwCustomer.getId(), tagId);
                                    if (wwCustomerTags == null) {//没有打此标签，则需要打标签
                                        wwCustomerTags = new WwCustomerTags();
                                        wwCustomerTags.setId(IdWorker.getId());
                                        wwCustomerTags.setTagId(tagId);
                                        wwCustomerTags.setTagIdStr(wwTags.getTagId());
                                        wwCustomerTags.setCustomerId(wwCustomer.getId());
                                        wwCustomerTags.setMerId(device.getMerId());
                                        wwCustomerTags.setCreateTime(now);
                                        wwCustomerTags.setUpdateTime(now);
                                        wwCustomerTagsMapper.insert(wwCustomerTags);
                                        //根据标签拉群
                                        groupPullConfigService.groupPushByEnterpriseTag(device, wwCustomer, wwCustomerTags.getTagId());
                                        //发送打标签指令
                                        try {
                                            MicaTriggerBatchMarkLabelMsg micaTriggerBatchMarkLabelMsg = new MicaTriggerBatchMarkLabelMsg();
                                            micaTriggerBatchMarkLabelMsg.setLabelId(wwTags.getTagId());
                                            micaTriggerBatchMarkLabelMsg.setIsCorp(Tools.getInteger(wwTags.getType()).intValue() == 1 ? true : false); //是否是企业标签
                                            micaTriggerBatchMarkLabelMsg.setAddWxIds(Lists.newArrayList(wwCustomer.getWxid()));
                                            MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerBatchMarkLabelMsg, MicaTriggerType.TRIGGER_BATCH_MARK_LABEL, Functions.fillTriggerMsg(device));
                                            sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC); //存放瞬时消息
                                        } catch (Exception e) {
                                            log.error("{}", e);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(), e);
        }finally {
            log.info("--监控系统日志--结束--");
        }
    }

    /**
     * 验证消息关键词打标签
     *
     * @param taskTagKeywordDevice 新好友申请实体类
     * @return 实例对象
     */
    private TaskTagKeywordVerifyResult verifyPara(TaskTagKeywordDevice taskTagKeywordDevice, String msg, Device device) {
        //返回对象
        TaskTagKeywordVerifyResult taskTagKeywordVerifyResult = new TaskTagKeywordVerifyResult();
        //默认为不通过
        taskTagKeywordVerifyResult.setPass(false);

        try {
            if (taskTagKeywordDevice == null) {
                return taskTagKeywordVerifyResult;
            }

            if (StringUtils.isBlank(msg)) {
                return taskTagKeywordVerifyResult;
            }

            //默认不通过
            boolean pass = false;

            //关键词类型(0-模糊关键词；1-精准关键词)
            Integer keywordType = Tools.getInteger(taskTagKeywordDevice.getKeywordType());
            //关键词模式(0-满足所有触发；1-满足一个触发)
            Integer keywordModel = Tools.getInteger(taskTagKeywordDevice.getKeywordModel());
            //关键词列表
            List<String> keywordList = JSONObject.parseArray(taskTagKeywordDevice.getKeywords(), String.class);
            //关键词列表
            if (keywordList == null || keywordList.size() == 0) {
                return taskTagKeywordVerifyResult;
            }

            //模糊关键词匹配
            if (keywordType.intValue() == 0) {
                if (keywordModel.intValue() == 0) { //满足所有触发
                    for (String keyword : keywordList) {
                        if (!msg.contains(keyword)) {//找到一个不符合的，就返回不通过
                            taskTagKeywordVerifyResult.setPass(false);
                            return taskTagKeywordVerifyResult;
                        }
                    }
                    taskTagKeywordVerifyResult.setPass(true);
                    return taskTagKeywordVerifyResult;
                } else {//满足一个触发
                    for (String keyword : keywordList) {
                        if (msg.contains(keyword)) {//找到一个符合的，就返回通过
                            taskTagKeywordVerifyResult.setPass(true);
                            return taskTagKeywordVerifyResult;
                        }
                    }
                }
            } else {//精准关键词
                if (keywordModel.intValue() == 0) { //满足所有触发
                    for (String keyword : keywordList) {
                        if (!msg.equals(keyword)) {//找到一个不符合的，就返回不通过
                            taskTagKeywordVerifyResult.setPass(false);
                            return taskTagKeywordVerifyResult;
                        }
                    }
                    taskTagKeywordVerifyResult.setPass(true);
                    return taskTagKeywordVerifyResult;
                } else {//满足一个触发
                    for (String keyword : keywordList) {
                        if (msg.equals(keyword)) {//找到一个符合的，就返回通过
                            taskTagKeywordVerifyResult.setPass(true);
                            return taskTagKeywordVerifyResult;
                        }
                    }
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(), e);
        }

        return taskTagKeywordVerifyResult;
    }

}
